package dk.gavdi.presentation;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Exceptions.ConverterException;
import Exceptions.HttpNodeClientException;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class RegistrationActivity extends Activity {

private static final String TAG = "RegistrationActivity";
private Bundle extras;
private ArrayAdapter<CharSequence> adapter;
private Spinner spinnerHours;
private Spinner spinnerWBS;
private Spinner spinnerDate;
private Button btnSubmitTime;
private Button btnBackToMenu;
private Button btnLogoutFromTime;
private AlertDialog.Builder builder;
private String userID;
private String wbs;
private String date;
private String hours;
private DialogInterface.OnClickListener dialogClickListener;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);
        
		spinnerWBS = (Spinner) findViewById(R.id.spinnerWBS);
		spinnerHours = (Spinner) findViewById(R.id.spinnerHours);
		spinnerDate = (Spinner) findViewById(R.id.spinnerDate);
		btnSubmitTime = (Button) findViewById(R.id.btnSubmitTime);
		btnBackToMenu = (Button) findViewById(R.id.btnBackToMenu);
		btnLogoutFromTime = (Button) findViewById(R.id.btnLogoutFromTime);
		createDialog();
		
		extras = new Bundle();
		extras = getIntent().getExtras();
		
		JSONArray arr;
		try {
			arr = Converter.createWBSArray(extras.getString("wbsArrayToday"));
			spinnerWBS.setAdapter(initSpinnerWBS(arr));
			spinnerHours.setAdapter(initSpinnerHours(Converter.getHourArray()));
			spinnerDate.setAdapter(initSpinnerDate());	
		} catch (ConverterException e) {
			e.printStackTrace();
		}
	
		spinnerDate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

			public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
				try{
					if ( i == 1)
					{
						JSONArray arr = Converter.createWBSArray(extras.getString("wbsArrayToday"));
						spinnerWBS.setAdapter(initSpinnerWBS(arr));
					}
					else if ( i == 2)
					{
						JSONArray arr = Converter.createWBSArray(extras.getString("wbsArrayYesterday"));
						spinnerWBS.setAdapter(initSpinnerWBS(arr));
					}
				}
				catch (ConverterException e){
					e.printStackTrace();
				}
			}
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
			}
		});
		
		btnSubmitTime.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				
				userID = extras.getString("userID");
				wbs = spinnerWBS.getSelectedItem().toString();
				date = spinnerDate.getSelectedItem().toString();
				date = date.substring(date.length() - 8);
				hours = spinnerHours.getSelectedItem().toString();
				
				if(submitCheck()){
                    String submitMessage = "Are you sure you want to register the following:\n\n"
                            			 + "User ID: "
                                         + userID
                                         + "\n"
                                         + "Date: "
                                         + date
                                         + "\n"
                                         + "WBS: " + wbs + "\n" + "Hours: " + hours;
                    builder.setMessage(submitMessage)
                            .setPositiveButton("Yes", dialogClickListener)
                            .setNegativeButton("No", dialogClickListener).show();
					
				}
				else{
                    String submitMessage = "Miss";
                    builder.setMessage(submitMessage)
                                             .setNegativeButton("Yes", dialogClickListener).show();
				}
				
			}
		});
		
		btnBackToMenu.setOnClickListener(new View.OnClickListener() {		
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(), MenuActivity.class);		
				intent.putExtras(extras);
				startActivity(intent);				
			}
		});
		
		btnLogoutFromTime.setOnClickListener(new View.OnClickListener() {		
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(), LoginActivity.class);		
				startActivity(intent);			
			}
		});
		
    }
    private ArrayAdapter<CharSequence> initSpinnerWBS(JSONArray arr){
		adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add("***Choose WBS-Element***");
		for(Integer i=0; i< arr.length(); i++){ 
			try{ 
        //Get My JSONObject and grab the String Value that I want. 
				JSONObject js = arr.getJSONObject(i);
				String wbs = js.getString("wbs");
        //Add the string to the adapter
                adapter.add(wbs); 
			}
			catch(JSONException e){ }
		}
		return adapter;
    }
    private ArrayAdapter<CharSequence> initSpinnerHours(String[] arr){
		adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		adapter.add("***Choose hours***");
		
		for(Integer i=0; i< arr.length; i++){ 
			//Get My JSONObject and grab the String Value that I want. 
					String hour = arr[i]; 
			//Add the string to the adapter
			        adapter.add(hour);
		}
		return adapter;
    }
    private ArrayAdapter<CharSequence> initSpinnerDate(){
		adapter = new ArrayAdapter<CharSequence>(
											 this, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add("***Choose date***");
		adapter.add("Today - " + extras.getString("dateToday"));
		adapter.add("Yesterday - " + extras.getString("dateYesterday"));

		return adapter;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_registration, menu);
        return true;
    }
	@Override 
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
	    if (keyCode == KeyEvent.KEYCODE_BACK) { 
			Intent intent = new Intent(getBaseContext(),LoginActivity.class);
			startActivity(intent);
	        return true; 
	    } 
	    return super.onKeyDown(keyCode, event); 
	} 
	private boolean submitCheck() {
        builder = new AlertDialog.Builder(this);
        int datePos = spinnerDate.getSelectedItemPosition();
        int hoursPos = spinnerHours.getSelectedItemPosition();
        int wbsPos = spinnerWBS.getSelectedItemPosition();

        if (datePos == 0 || hoursPos == 0 || wbsPos == 0) {            
        	return false;
        } 
        else {
        	return true;
        }
}

	private void createDialog(){
		
		dialogClickListener = new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int which) {
		                switch (which) {
		                case DialogInterface.BUTTON_POSITIVE:
							JSONObject jsonObj = null;
							try {
								jsonObj = Converter.createTimeRegJSON(userID, wbs, date, hours);
								HttpNodeClient.sendJSON(jsonObj);
							} catch (ConverterException e) {
								e.printStackTrace();
								Log.i(TAG, e.getError());
							} catch (HttpNodeClientException e){
								e.printStackTrace();
								Log.i(TAG, e.getError());
							}
		                             
		                             break;

		                case DialogInterface.BUTTON_NEGATIVE:
		                             break;
		                case DialogInterface.BUTTON_NEUTRAL:
		                             break;
		                }
		    }
		};
	}



}
